#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
权限维持系统日志分析器演示脚本
演示如何使用log_analyzer.sh生成合规审计报告
"""

import os
import sys
import json
import time
import subprocess
import tempfile
from datetime import datetime, timedelta
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 尝试导入标准日志记录器，如果失败则使用简化版本
try:
    from modules.standard_logger import StandardLogger, LogLevel, LogFacility, SIEMFormat
    HAS_STANDARD_LOGGER = True
except ImportError:
    HAS_STANDARD_LOGGER = False
    # 定义简化的日志级别枚举
    class LogLevel:
        INFO = "INFO"
        WARNING = "WARNING"
        ERROR = "ERROR"
        DEBUG = "DEBUG"

class LogAnalyzerDemo:
    """日志分析器演示类"""
    
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.log_dir = self.project_root / "logs" / "demo"
        self.output_dir = self.project_root / "reports" / "demo"
        self.analyzer_script = self.project_root / "scripts" / "log_analyzer.sh"
        
        # 创建必要的目录
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        
        # 初始化标准日志记录器（如果可用）
        if HAS_STANDARD_LOGGER:
            self.logger = StandardLogger(
                name="log_analyzer_demo",
                log_file=str(self.log_dir / "demo.log"),
                enable_syslog=False,  # 在Windows环境下禁用syslog
                enable_siem=True,
                siem_format=SIEMFormat.JSON
            )
        else:
            self.logger = None
            print("⚠️  标准日志记录器不可用，使用简化模式")
        
        print(f"📁 演示日志目录: {self.log_dir}")
        print(f"📁 报告输出目录: {self.output_dir}")
        print(f"🔧 分析器脚本: {self.analyzer_script}")
        print()
    
    def generate_sample_logs(self):
        """生成示例日志数据"""
        print("🔄 生成示例日志数据...")
        
        # 生成不同类型的日志事件
        sample_events = [
            # 系统事件
            {
                "level": "INFO",
                "message": "权限维持系统启动完成",
                "event_type": "system",
                "component": "core"
            },
            {
                "level": "INFO",
                "message": "环境检测模块初始化",
                "event_type": "system",
                "component": "env_detector"
            },
            {
                "level": "INFO",
                "message": "云环境适配模块加载 - AWS EC2",
                "event_type": "system",
                "component": "cloud_detector"
            },
            
            # 安全事件
            {
                "level": "WARNING",
                "message": "检测到EDR进程: Windows Defender",
                "event_type": "security",
                "component": "edr_detector"
            },
            {
                "level": "INFO",
                "message": "应用EDR规避策略: 进程隐藏",
                "event_type": "security",
                "component": "edr_evasion"
            },
            {
                "level": "WARNING",
                "message": "检测到BPF监控活动",
                "event_type": "security",
                "component": "bpf_detector"
            },
            {
                "level": "INFO",
                "message": "启动BPF对抗措施",
                "event_type": "security",
                "component": "bpf_evasion"
            },
            
            # 审计事件
            {
                "level": "INFO",
                "message": "用户权限提升操作",
                "event_type": "audit",
                "component": "privilege_escalation",
                "user": "demo_user"
            },
            {
                "level": "INFO",
                "message": "文件访问记录: /etc/passwd",
                "event_type": "audit",
                "component": "file_access",
                "file_path": "/etc/passwd"
            },
            {
                "level": "INFO",
                "message": "网络连接建立: 192.168.1.100:443",
                "event_type": "audit",
                "component": "network",
                "remote_ip": "192.168.1.100",
                "remote_port": 443
            },
            
            # 错误事件
            {
                "level": "ERROR",
                "message": "权限提升失败: 访问被拒绝",
                "event_type": "error",
                "component": "privilege_escalation",
                "error_code": "ACCESS_DENIED"
            },
            {
                "level": "ERROR",
                "message": "配置文件读取失败",
                "event_type": "error",
                "component": "config_loader",
                "file_path": "/etc/privilege_ma.conf"
            },
            
            # 警告事件
            {
                "level": "WARNING",
                "message": "磁盘空间不足警告",
                "event_type": "warning",
                "component": "system_monitor",
                "disk_usage": "85%"
            },
            {
                "level": "WARNING",
                "message": "内存使用率过高",
                "event_type": "warning",
                "component": "system_monitor",
                "memory_usage": "92%"
            },
            
            # 痕迹清理事件
            {
                "level": "INFO",
                "message": "开始痕迹清理操作",
                "event_type": "cleanup",
                "component": "trace_cleaner"
            },
            {
                "level": "INFO",
                "message": "清理临时文件: 15个文件",
                "event_type": "cleanup",
                "component": "trace_cleaner",
                "files_cleaned": 15
            },
            {
                "level": "INFO",
                "message": "清理网络连接记录",
                "event_type": "cleanup",
                "component": "trace_cleaner"
            },
            {
                "level": "INFO",
                "message": "痕迹清理完成 - 成功率: 95%",
                "event_type": "cleanup",
                "component": "trace_cleaner",
                "success_rate": "95%"
            }
        ]
        
        # 生成多天的日志数据
        base_time = datetime.now() - timedelta(days=7)
        
        for day in range(7):
            current_date = base_time + timedelta(days=day)
            daily_log_file = self.log_dir / f"privilege_ma_{current_date.strftime('%Y%m%d')}.log"
            
            with open(daily_log_file, 'w', encoding='utf-8') as f:
                # 每天生成多个事件
                for hour in range(0, 24, 2):  # 每2小时一个事件
                    for event in sample_events[:5]:  # 每次选择前5个事件
                        event_time = current_date.replace(hour=hour, minute=0, second=0)
                        
                        # 写入标准日志格式
                        log_line = f"{event_time.strftime('%Y-%m-%d %H:%M:%S')} [{event['level']}] privilege_ma.{event['component']}: {event['message']}"
                        f.write(log_line + "\n")
                        
                        # 写入JSON格式
                        json_event = {
                            "timestamp": event_time.isoformat(),
                            "level": event['level'],
                            "component": event['component'],
                            "message": event['message'],
                            "event_type": event['event_type'],
                            **{k: v for k, v in event.items() if k not in ['level', 'message', 'event_type', 'component']}
                        }
                        f.write(f"JSON: {json.dumps(json_event, ensure_ascii=False)}\n")
        
        # 生成主日志文件
        main_log_file = self.log_dir / "privilege_ma.log"
        with open(main_log_file, 'w', encoding='utf-8') as f:
            for event in sample_events:
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                log_line = f"{timestamp} [{event['level']}] privilege_ma.{event['component']}: {event['message']}"
                f.write(log_line + "\n")
        
        print(f"✅ 已生成 {len(list(self.log_dir.glob('*.log')))} 个示例日志文件")
        print(f"📊 总计生成约 {len(sample_events) * 7 * 12} 条日志记录")
        print()
    
    def run_log_analyzer(self, output_format="html"):
        """运行日志分析器"""
        print(f"🔍 运行日志分析器 (格式: {output_format})...")
        
        # 检查分析器脚本是否存在
        if not self.analyzer_script.exists():
            print(f"❌ 分析器脚本不存在: {self.analyzer_script}")
            return False
        
        try:
            # 构建命令
            cmd = [
                "bash",
                str(self.analyzer_script),
                "--log-dir", str(self.log_dir),
                "--output-dir", str(self.output_dir),
                "--days", "7",
                "--format", output_format,
                "--verbose"
            ]
            
            print(f"🔧 执行命令: {' '.join(cmd)}")
            
            # 在Windows环境下，我们模拟分析器的输出
            if os.name == 'nt':
                print("⚠️  检测到Windows环境，模拟日志分析器输出...")
                return self.simulate_analyzer_output(output_format)
            
            # 在Linux环境下运行实际的脚本
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=300  # 5分钟超时
            )
            
            if result.returncode == 0:
                print("✅ 日志分析完成")
                print(f"📄 输出:\n{result.stdout}")
                return True
            else:
                print(f"❌ 日志分析失败 (退出码: {result.returncode})")
                print(f"错误信息:\n{result.stderr}")
                return False
                
        except subprocess.TimeoutExpired:
            print("❌ 日志分析超时")
            return False
        except Exception as e:
            print(f"❌ 运行日志分析器时出错: {e}")
            return False
    
    def simulate_analyzer_output(self, output_format):
        """模拟分析器输出（用于Windows环境）"""
        print("🔄 模拟日志分析过程...")
        
        # 模拟分析统计
        stats = {
            "total_events": 504,  # 7天 * 12小时 * 6事件
            "security_events": 168,
            "system_events": 126,
            "audit_events": 126,
            "error_events": 42,
            "warning_events": 42
        }
        
        # 生成模拟报告
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        
        if output_format == "html":
            report_file = self.output_dir / f"privilege_ma_audit_report_{timestamp}.html"
            self.generate_mock_html_report(report_file, stats)
        elif output_format == "json":
            report_file = self.output_dir / f"privilege_ma_audit_report_{timestamp}.json"
            self.generate_mock_json_report(report_file, stats)
        elif output_format == "csv":
            report_file = self.output_dir / f"privilege_ma_audit_report_{timestamp}.csv"
            self.generate_mock_csv_report(report_file, stats)
        elif output_format == "txt":
            report_file = self.output_dir / f"privilege_ma_audit_report_{timestamp}.txt"
            self.generate_mock_txt_report(report_file, stats)
        
        print(f"✅ 模拟报告已生成: {report_file}")
        return True
    
    def generate_mock_html_report(self, report_file, stats):
        """生成模拟HTML报告"""
        html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>权限维持系统审计报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }}
        .container {{ max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
        .header {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; text-align: center; border-radius: 8px; margin-bottom: 20px; }}
        .stats-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }}
        .stat-card {{ background: #f8f9fa; border-left: 4px solid #667eea; padding: 15px; border-radius: 4px; }}
        .stat-card h3 {{ margin: 0 0 10px 0; color: #667eea; }}
        .stat-card .number {{ font-size: 1.8em; font-weight: bold; color: #333; }}
        .alert {{ padding: 15px; border-radius: 4px; margin-bottom: 15px; }}
        .alert-info {{ background-color: #d1ecf1; border-color: #bee5eb; color: #0c5460; }}
        .alert-warning {{ background-color: #fff3cd; border-color: #ffeaa7; color: #856404; }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>权限维持系统审计报告</h1>
            <p>生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
        </div>
        
        <div class="stats-grid">
            <div class="stat-card">
                <h3>总事件数</h3>
                <div class="number">{stats['total_events']}</div>
            </div>
            <div class="stat-card">
                <h3>安全事件</h3>
                <div class="number">{stats['security_events']}</div>
            </div>
            <div class="stat-card">
                <h3>系统事件</h3>
                <div class="number">{stats['system_events']}</div>
            </div>
            <div class="stat-card">
                <h3>审计事件</h3>
                <div class="number">{stats['audit_events']}</div>
            </div>
            <div class="stat-card">
                <h3>错误事件</h3>
                <div class="number">{stats['error_events']}</div>
            </div>
            <div class="stat-card">
                <h3>警告事件</h3>
                <div class="number">{stats['warning_events']}</div>
            </div>
        </div>
        
        <div class="alert alert-info">
            <strong>分析周期:</strong> 最近7天的日志数据
        </div>
        
        <div class="alert alert-warning">
            <strong>风险评估:</strong> 检测到 {stats['error_events']} 个错误事件，建议进一步调查
        </div>
        
        <h2>建议措施</h2>
        <ul>
            <li>定期监控系统日志，及时发现异常活动</li>
            <li>保持系统和安全工具的最新版本</li>
            <li>建立完善的事件响应流程</li>
            <li>定期进行安全审计和风险评估</li>
        </ul>
    </div>
</body>
</html>
        """
        
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
    
    def generate_mock_json_report(self, report_file, stats):
        """生成模拟JSON报告"""
        report_data = {
            "report_info": {
                "timestamp": datetime.now().isoformat(),
                "generator": "privilege_ma_log_analyzer_demo",
                "version": "1.0",
                "analysis_period_days": 7
            },
            "statistics": stats,
            "risk_assessment": {
                "risk_level": "medium",
                "risk_score": 65,
                "recommendations": [
                    "监控错误事件",
                    "优化系统性能",
                    "加强安全防护"
                ]
            },
            "compliance": {
                "status": "compliant",
                "score": 85,
                "checks_passed": 8,
                "checks_failed": 2
            }
        }
        
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report_data, f, ensure_ascii=False, indent=2)
    
    def generate_mock_csv_report(self, report_file, stats):
        """生成模拟CSV报告"""
        csv_content = """Timestamp,Level,Event Type,Message,Source,Component
2024-01-15 10:00:00,INFO,system,权限维持系统启动完成,privilege_ma,core
2024-01-15 10:01:00,INFO,system,环境检测模块初始化,privilege_ma,env_detector
2024-01-15 10:02:00,WARNING,security,检测到EDR进程: Windows Defender,privilege_ma,edr_detector
2024-01-15 10:03:00,INFO,security,应用EDR规避策略: 进程隐藏,privilege_ma,edr_evasion
2024-01-15 10:04:00,INFO,audit,用户权限提升操作,privilege_ma,privilege_escalation
2024-01-15 10:05:00,ERROR,error,权限提升失败: 访问被拒绝,privilege_ma,privilege_escalation
2024-01-15 10:06:00,WARNING,warning,磁盘空间不足警告,privilege_ma,system_monitor
2024-01-15 10:07:00,INFO,cleanup,开始痕迹清理操作,privilege_ma,trace_cleaner
"""
        
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write(csv_content)
    
    def generate_mock_txt_report(self, report_file, stats):
        """生成模拟文本报告"""
        txt_content = f"""权限维持系统审计报告
====================

生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
分析器版本: 1.0 (演示版)

报告摘要
--------
总事件数: {stats['total_events']}
安全事件: {stats['security_events']}
系统事件: {stats['system_events']}
审计事件: {stats['audit_events']}
错误事件: {stats['error_events']}
警告事件: {stats['warning_events']}

分析周期: 7 天

风险评估
--------
⚠️  中风险: 检测到 {stats['error_events']} 个错误事件
⚠️  中风险: 检测到 {stats['warning_events']} 个警告事件

建议措施
--------
1. 定期监控系统日志，及时发现异常活动
2. 保持系统和安全工具的最新版本
3. 建立完善的事件响应流程
4. 定期进行安全审计和风险评估

合规性检查
----------
✅ 基本安全要求: 通过
✅ 日志记录规范: 通过
⚠️  错误处理机制: 需要改进
⚠️  性能监控: 需要加强
"""
        
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write(txt_content)
    
    def display_report_summary(self):
        """显示报告摘要"""
        print("📋 生成的报告文件:")
        
        report_files = list(self.output_dir.glob("privilege_ma_audit_report_*"))
        if not report_files:
            print("❌ 未找到报告文件")
            return
        
        for report_file in sorted(report_files):
            file_size = report_file.stat().st_size
            print(f"  📄 {report_file.name} ({file_size:,} 字节)")
        
        print(f"\n📁 报告目录: {self.output_dir}")
        print()
    
    def run_demo(self):
        """运行完整演示"""
        print("🚀 权限维持系统日志分析器演示")
        print("=" * 50)
        print()
        
        try:
            # 1. 生成示例日志
            self.generate_sample_logs()
            
            # 2. 运行不同格式的分析
            formats = ["html", "json", "csv", "txt"]
            
            for fmt in formats:
                print(f"📊 生成 {fmt.upper()} 格式报告...")
                success = self.run_log_analyzer(fmt)
                if success:
                    print(f"✅ {fmt.upper()} 报告生成成功")
                else:
                    print(f"❌ {fmt.upper()} 报告生成失败")
                print()
                time.sleep(1)  # 避免时间戳冲突
            
            # 3. 显示报告摘要
            self.display_report_summary()
            
            # 4. 演示完成
            print("🎉 日志分析器演示完成!")
            print()
            print("💡 使用说明:")
            print("1. 查看生成的报告文件了解系统运行状态")
            print("2. HTML报告提供最佳的可视化体验")
            print("3. JSON报告适合程序化处理")
            print("4. CSV报告便于数据分析")
            print("5. TXT报告适合快速查看")
            print()
            print("🔧 自定义使用:")
            print(f"bash {self.analyzer_script} --log-dir /your/log/path --format html")
            
        except KeyboardInterrupt:
            print("\n⚠️  演示被用户中断")
        except Exception as e:
            print(f"\n❌ 演示过程中出错: {e}")
            import traceback
            traceback.print_exc()

def main():
    """主函数"""
    demo = LogAnalyzerDemo()
    demo.run_demo()

if __name__ == "__main__":
    main()